package com.narbeshuber.tablet.lasalara.http;


import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.ByteArrayBuffer;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;

import com.narbeshuber.tablet.lasalara.R;
import com.narbeshuber.tablet.lasalara.fragment.LoginFragment;
import com.narbeshuber.tablet.lasalara.fragment.LoginFragment.ErrorField;

public class RetrievePasswordTask extends AsyncTask<String, Object, String> {

	Activity lasalaraActivity;
	ProgressDialog dialog;
	public RetrievePasswordTask(Activity lasalaraActivity){
		this.lasalaraActivity = lasalaraActivity;
	}
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		dialog = ProgressDialog.show(lasalaraActivity, "", "Sending password. Please wait...", true);
	}
	
	@Override
	protected String doInBackground(String... arg0) {
		
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost("http://1.narbeshuber.appspot.com/email");
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
		String email = arg0[0].toLowerCase();
		nameValuePairs.add(new BasicNameValuePair("em", email));
		try {
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			InputStream is = response.getEntity().getContent();
			BufferedInputStream bis = new BufferedInputStream(is, 700);				 				
			ByteArrayBuffer baf = new ByteArrayBuffer(20);
			int current = 0;
			while ((current = bis.read()) != -1) {
					baf.append((byte) current);
				}		
			final String retval = new String(baf.toByteArray());
			return retval;
		} catch (Exception e) {
			Log.e("Exception: ", e.getMessage());
		}
		return null;
	}

	 protected void onPostExecute(String result) {
		dialog.dismiss();
		TextView errorMessage = (TextView) lasalaraActivity.findViewById(R.id.error_field);	
		try {
			if(result.equals("0")){
				LoginFragment.setErrorText("Unknow e-mail address", ErrorField.LOGIN_EMAIL);
			}else{
				LoginFragment.setErrorText("Password sent", ErrorField.LOGIN_EMAIL);
			}
		} catch (Exception e) {
			Log.e("Exception: ", e.getMessage());
		}
	 }
}
